package utils

import (
	"fmt"
	"strings"
)

// ParamFormat 拼接sql的where条件
func ParamFormat(whereArgs map[string]string, withoutQuote []string) string {
	whereString := ""
	for k, v := range whereArgs {
		if k != "limit" && k != "offset" {
			if v != "" {
				isQuoted := true // 是否需要引号包裹
				for _, s := range withoutQuote {
					if k == s {
						isQuoted = false
						break
					}
				}
				if isQuoted {
					whereString += fmt.Sprintf(" %s='%s' AND", k, v)
				} else {
					whereString += fmt.Sprintf(" %s=%s AND", k, v)
				}
			}
		}
	}
	if strings.HasSuffix(whereString, "AND") {
		whereString = whereString[:len(whereString)-4]
	}
	if whereString != "" {
		whereString = strings.Join([]string{" WHERE", whereString}, "")
	}
	limit := whereArgs["limit"]
	offset := whereArgs["offset"]
	if offset == "" {
		offset = "0"
	}
	if limit == "" {
		limit = "10"
	}
	return fmt.Sprintf("%s LIMIT %s,%s", whereString, offset, limit)
}
